package com.github.ginirohikocha.dbm.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.RequestCode;
import com.github.ginirohikocha.dbm.adapter.RecycleOfferAdapter;
import com.github.ginirohikocha.dbm.dialog.CompleteCustomerDialog;
import com.github.ginirohikocha.dbm.entity.OrderIncludeCustomerWorker;
import com.github.ginirohikocha.dbm.util.HttpUtil;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderDetailActivity extends AppCompatActivity {

    private boolean isInit = true;

    private SharedPreferences workerInfo;
    private Bundle savedInstanceState;

    private OrderIncludeCustomerWorker order;

    private ZLoadingDialog dialog;

    private CoordinatorLayout coordinatorLayout;
    private LinearLayout titleMain, orderOffer, offerTitle, completeCustomer;
    private RecyclerView offerContent;
    private NestedScrollView bottomSheet;
    private TextView title,
            faultType, faultDescription,
            contactName, contactMobilePhone, contactAddress,
            offerPrice,
            orderNum, orderTime, orderType;
    private Button operMain, operSub;
    private MapView mapView;

    private RecycleOfferAdapter offerAdapter;
    private BottomSheetBehavior behavior;

    private BaiduMap map;
    private LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        this.savedInstanceState = savedInstanceState;

        order = (OrderIncludeCustomerWorker)getIntent().getSerializableExtra("order");
        workerInfo = getSharedPreferences("worker", 0);
        dialog = new ZLoadingDialog(OrderDetailActivity.this);//加载动画
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.BLACK)//颜色
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .setHintText("加载中...");
        //初始绑定
        coordinatorLayout = findViewById(R.id.activity_order_coordinator);
        bottomSheet = findViewById(R.id.activity_order_bottom_sheet);
        offerContent = findViewById(R.id.activity_order_offer_content);
        orderOffer = findViewById(R.id.activity_order_offer);
        titleMain = findViewById(R.id.activity_order_title);
        title = findViewById(R.id.activity_order_title_text);
        faultType = findViewById(R.id.activity_order_faultType);
        faultDescription = findViewById(R.id.activity_order_faultDescription);
        contactName = findViewById(R.id.activity_order_contactName);
        contactMobilePhone = findViewById(R.id.activity_order_contactMobilePhone);
        contactAddress = findViewById(R.id.activity_order_contactAddress);
        offerTitle = findViewById(R.id.activity_order_offerTitle);
        offerPrice = findViewById(R.id.activity_order_offer_price);
        orderNum = findViewById(R.id.activity_order_orderNum);
        orderType = findViewById(R.id.activity_order_orderType);
        orderTime = findViewById(R.id.activity_order_orderTime);
        mapView = findViewById(R.id.activity_order_map);
        operMain = findViewById(R.id.activity_order_operationMain);
        operSub = findViewById(R.id.activity_order_operationSub);
        completeCustomer = findViewById(R.id.activity_order_completeCustom);

        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        //获取订单详细信息
        getOrderDetail();
    }

    /**
     * 初始化组件
     * **/
    private void initComponent() throws NullPointerException{
        title.setText(order.transferStatus());
        faultType.setText(order.getFaultName());
        faultDescription.setText(order.getFaultDescription());
        contactName.setText(order.getContactName());
        contactMobilePhone.setText(order.getContactPhone());
        contactAddress.setText(order.getContactAddress());
        orderNum.setText(order.getOrderNum());
        orderType.setText(order.getType());
        orderTime.setText(String.format(Locale.CHINESE, "%tF %tT", order.getOrdertime(), order.getOrdertime()));
        initOper();
        //主操作点击进行操作
        operMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeOperation();
            }
        });
        //副操作点击进行操作
        operSub.setText(getResources().getString(R.string.oper_hand_over));
        operSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
                updateOrder(2);
            }
        });
        //协助完成户主信息
        completeCustomer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CompleteCustomerDialog dialog = new CompleteCustomerDialog(OrderDetailActivity.this, order);
                dialog.show();
            }
        });
        //价格设定
        if (order.getEstimatedPrice() == null)
            offerPrice.setText(getResources().getString(R.string.activity_order_offer_defaultPrice));
        else
            offerPrice.setText(String.format(Locale.CHINESE, "%.2f", order.getEstimatedPrice()));
        //业务列表适配器初始化
        if (isAccepted(order.getStatus())) {//是否已接单
            orderOffer.setVisibility(View.VISIBLE);
            if (offerAdapter == null)
                initRecycleAdapter();
            else {
                offerAdapter.refresh(order.getOrderNum());
            }
            //打开业务添加界面
            offerTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (order.getStatus().equals("已接单")) {
                        Intent intent = new Intent(OrderDetailActivity.this, OffersActivity.class);
                        intent.putExtra("orderNum", order.getOrderNum());
                        startActivityForResult(intent, RequestCode.REQUEST_OFFERS);
                    } else {
                        Toast.makeText(OrderDetailActivity.this, "客户已确认报价，无法进行修改", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            if (!isFinished(order.getStatus())) {//是否未完成
                orderOffer.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityForResult(new Intent(OrderDetailActivity.this, OffersActivity.class), 105);
                    }
                });
                //BottomSheet相关
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                mapView.setVisibility(View.VISIBLE);
                initMap();
                behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                    @Override
                    public void onStateChanged(@NonNull View view, int i) {
                        switch (i) {
                            case BottomSheetBehavior.STATE_EXPANDED:
                                bottomSheet.setBackgroundColor(getResources().getColor(R.color.defaultBackground));
                                titleMain.setVisibility(View.VISIBLE);
                                break;
                            case BottomSheetBehavior.STATE_DRAGGING:
                            case BottomSheetBehavior.STATE_SETTLING:
                                bottomSheet.setBackground(null);
                                titleMain.setVisibility(View.INVISIBLE);
                                break;
                            case BottomSheetBehavior.STATE_COLLAPSED:
                                titleMain.setVisibility(View.GONE);
                                break;
                        }
                    }

                    @Override
                    public void onSlide(@NonNull View view, float v) {

                    }
                });
            } else {
                behavior.setPeekHeight(coordinatorLayout.getHeight());
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                mapView.setEnabled(false);
                destroyMap();
                bottomSheet.setBackgroundColor(getResources().getColor(R.color.defaultBackground));
            }
        }

        //恢复之前的状态
        if (savedInstanceState != null) {
            behavior.setState(savedInstanceState.getInt("behaviorState"));
        }
    }

    /**
     * 初始化列表，没有必要不需要被调用第二次
     * **/
    private void initRecycleAdapter() {
        offerAdapter = new RecycleOfferAdapter(this, order.getOrderNum());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        offerContent.setLayoutManager(layoutManager);
        offerContent.setAdapter(offerAdapter);
    }

    private void initMap() {
        map = mapView.getMap();
        map.setMyLocationEnabled(true);
        locationClient = new LocationClient(getApplicationContext());

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(	5000);

        locationClient.setLocOption(option);
        locationClient.registerLocationListener(new MyLocationListener());
        locationClient.start();

//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                Log.d("Order定位", String.valueOf(locationClient.isStarted()));
//                locationClient.restart();
//            }
//        }, 0, 5000);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.d("位置接受", "位置更新");
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            map.setMyLocationData(locData);

            if (isInit) {
                MapStatus builder = new MapStatus.Builder()
                        .target(new LatLng(locData.latitude, locData.longitude))
                        .zoom(18.0f)
                        .build();
                map.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder));
                isInit = false;
            }
        }
    }

    /**
     * 获取订单
     * **/
    private void getOrderDetail() {
        setLoading(true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNum", getIntent().getStringExtra("orderNum"));

        HttpUtil.sendOkHttpPostRequest(Address.ORDER_QUERY, RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString()), new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Intent result = new Intent();
                result.putExtra("msg", "订单获取失败，请检查网络状态");
                setResult(RESULT_OK, result);
                setLoading(false);
                finish();
            }

            @Override
            public void onResponse(@NonNull Call call,@NonNull Response response) throws IOException {
                String responseBody = null;
                if (response.body() != null)
                    responseBody = response.body().string();
                Log.d("订单详情获取", responseBody);
                final JSONObject json = JSONObject.parseObject(responseBody);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            order = json.getJSONObject("page").getJSONArray("records").getObject(0, OrderIncludeCustomerWorker.class);
                            try {
                                Thread.sleep(400);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            initComponent();
                            setLoading(false);
                        } catch (Exception e) {
                            Log.w("订单详情获取", e.getMessage());
                            Intent result = new Intent();
                            result.putExtra("msg", "订单数据错误，获取失败");
                            setResult(RESULT_OK, result);
                            setLoading(false);
                            finish();
                        }
                    }
                });
            }
        });
    }

    /**
     * 刷新显示
     * **/
    public void refresh() {
        getOrderDetail();
    }

    public void setLoading(boolean b) {
        if (b) {
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RequestCode.REQUEST_OFFERS:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(OrderDetailActivity.this, "提交成功，请等待客户确认价格", Toast.LENGTH_LONG).show();
                    refresh();
                }
                break;
            case RequestCode.REQUEST_OFFER_DETAIL:
                if (resultCode == RESULT_CANCELED) {
                    String msg;
                    if (data != null){
                        msg = data.getStringExtra("msg");
                        if (msg != null)
                            Toast.makeText(OrderDetailActivity.this, msg, Toast.LENGTH_LONG).show();
                    }
                }
                if (resultCode == RESULT_OK) {
                    Toast.makeText(OrderDetailActivity.this, "操作成功", Toast.LENGTH_LONG).show();
                    offerAdapter.refresh(order.getOrderNum());
                }
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("behaviorState", behavior.getState());
    }

    /**
     * 状态判断
     * **/
    public boolean isAccepted(String status) {
        if (status == null||
                status.equals("待派单") ||
                status.equals("待接单") ||
                status.equals("已移交"))
            return false;
        return true;
    }

    public boolean isFinished(String status) {
        if (status == null||
                status.equals("待派单") ||
                status.equals("待接单") ||
                status.equals("已移交") ||
                status.equals("已接单") ||
                status.equals("已确认"))
            return false;
        return true;
    }

    private void initOper() {
        String status = order.getStatus();
        switch (status) {
            case "待派单":
            case "待接单":
                operMain.setText(R.string.oper_accept);
                break;
            case "已确认":
                operMain.setText(R.string.oper_finish);
                break;
            case "已完成":
                operMain.setText(R.string.oper_collect);
                break;
            default:
                operSub.setVisibility(View.GONE);
            case "已接单":
                operMain.setVisibility(View.GONE);
                break;
        }
    }

    private void executeOperation() {
        String status = operMain.getText().toString();
        switch (status) {
            case "接单":
                updateOrder(0);
                break;
            case "完成":
                updateOrder(1);
                break;
            case "确认收款":
                updateOrder(3);
                break;
        }
    }

    /**
     * @param type 0=接单;1=完成;2=移交;3=确认收款
     * **/
    private void updateOrder(final int type) {
        JSONObject jsonObject = new JSONObject();
        order.setWorkerid(workerInfo.getInt("id", -1));
        if (order.getWorkerid() == -1) {
            Toast.makeText(OrderDetailActivity.this, "数据错误", Toast.LENGTH_LONG).show();
            return;
        }
        jsonObject.put("order", order);

        switch (type){
            case 0:
                jsonObject.put("newStatus", "已接单");
                break;
            case 1:
                jsonObject.put("newStatus", "已完成");
                break;
            case 2:
                jsonObject.put("newStatus", "已移交");
                break;
            case 3:
                jsonObject.put("newStatus", "已付款");
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString());

        HttpUtil.sendOkHttpPostRequest(Address.ORDER_UPDATE, requestBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(OrderDetailActivity.this, "网络连接错误", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseBody = response.body().string();
                Log.d("订单更新", responseBody);
                final JSONObject json = JSON.parseObject(responseBody);
                if (json.getBoolean("succ")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OrderDetailActivity.this, "操作成功", Toast.LENGTH_LONG).show();
                            if (type == 3)
                                finish();
                            else
                                refresh();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OrderDetailActivity.this, json.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
    }
    /*
    * 地图处理
    * */
    @Override
    protected void onResume() {
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mapView != null)
            mapView.onResume();
        super.onResume();
    }
    @Override
    protected void onPause() {
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mapView != null)
            mapView.onPause();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mapView != null)
            destroyMap();
        super.onDestroy();
    }

    private void destroyMap() {
        if (locationClient != null)
            locationClient.stop();
        if (map != null)
            map.setMyLocationEnabled(false);
        if (mapView != null)
            mapView.onDestroy();
        mapView = null;
    }
}
